package com.zpark.dao.impl;

import com.zpark.dao.CourseDao;
import com.zpark.entity.Course;
import com.zpark.entity.Student;
import com.zpark.utils.DaoUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CourseDaoImpl implements CourseDao {
    @Override
    public void insert(Course course) {
        String sql = "insert into course(name) values (?)";
        try {
            DaoUtil.executeUpdate(sql,course.getName());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(Integer id, Course course) {
        String sql = "update course set name = ? where id = ?";
        try {
            DaoUtil.executeUpdate(sql,course.getName(),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(Integer id) {
        String sql = "delete from course where id = ?";
        try {
            DaoUtil.executeUpdate(sql,id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Course selectById(Integer id) {
        String sql = "SELECT * FROM course WHERE id=?";
        try (ResultSet rs = DaoUtil.executeQuery(sql, id)) {
            if (rs.next()) {
                return mapResultSetToCourse(rs);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Course> selectByPage(Integer size, int limitNumber) {
        String sql = "SELECT * FROM course LIMIT ?,?";
        List<Course> courses = new ArrayList<>();
        try (ResultSet rs = DaoUtil.executeQuery(sql,limitNumber,size)) {
            while (rs.next()) {
                courses.add(mapResultSetToCourse(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return courses;
    }


    private Course mapResultSetToCourse(ResultSet rs) throws SQLException {
        Course course = new Course();
        course.setId(rs.getInt("id"));
        course.setName(rs.getString("name"));
        return course;
    }
}
